package com.javasm.gg;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.javasm.commons.base.BaseController;
import com.javasm.commons.entity.AxiosResult;
import com.javasm.commons.entity.TableDatas;
import com.javasm.commons.enums.E;
import com.javasm.sys.tree.TreeUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("goodsType")
public class GoodsTypeController extends BaseController {
    @Resource
    private GoodsTypesService pts;
    @Resource
    private BrandService brandService;

    @GetMapping("getTree")
    public AxiosResult getTree(){
        List<GoodsType> all = pts.list();
        List<GoodsType> goodsTypes = TreeUtil.buildGoodsTypeTree(all,"-1");

        if (all==null||all.size()==0) return AxiosResult.error(E.NOT_EXISTS);
        return suc(goodsTypes);
    }

    @GetMapping
    public AxiosResult getByPage(GoodsType pt){
        startPage();
        List<GoodsType> allByPage = pts.list(new QueryWrapper(pt));
        if (allByPage==null||allByPage.size()==0) return AxiosResult.error(E.NOT_EXISTS);
        TableDatas td = new TableDatas(allByPage);
        return suc(td);
    }

    @GetMapping("{goodsTypeId}")
    public AxiosResult getChooseBrand(@PathVariable String goodsTypeId){
        List<Brand> list = brandService.list();//全部
        List<Brand> chooseBrand = brandService.getChooseBrand(goodsTypeId);//已选中
        Map<String,List> map =new HashMap<>();
        map.put("dataBrand",list);
        map.put("valBrand",chooseBrand);
        return suc(map);
    }

    @GetMapping("chooseBrand")
    public AxiosResult chooseBrand(String goodsTypeId,Integer[] brandIds){
        boolean b = pts.setChooseBrands2GoodsType(goodsTypeId, brandIds);
        if (b)return suc();
        return AxiosResult.error(E.OPERATION_FAILED);
    }

    @PostMapping
    public AxiosResult addForm(@RequestBody GoodsType pt){
        String id=pts.getnextId(pt.getPid());
        pt.setId(id);
        boolean b = pts.save(pt);
        if (b) return suc();
        return AxiosResult.error(E.OPERATION_FAILED);
    }

    @PutMapping
    public AxiosResult edit(@RequestBody GoodsType pt){
        boolean b = pts.updateById(pt);
        if (b) return suc();
        return AxiosResult.error(E.OPERATION_FAILED);
    }

    @DeleteMapping
    public AxiosResult delMany(String ids){
        String[] split = ids.split(",");
        boolean b = pts.removeByIds(Arrays.asList(split));
        if (b) return suc();
        return AxiosResult.error(E.OPERATION_FAILED);
    }
}
